using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.FormsManagement;

namespace InsightMigrationUtility
{
    public partial class MigrationMain : Form
    {
        private const string SelectDatabase = "-- Select Database --";
        private const string SelectQuestionnaireType = "-- Select Type --";
        private DBAccess sourceDBAccess;
        private DBAccess destinationDBAccess;
        private ArrayList sourceQuestionnaires;
        private ArrayList destinationQuestionnaires;

        public MigrationMain()
        {
            InitializeComponent();
        }

        private void InitDBAccess(Button sender)
        {
            if (sender.Name == "btnConnectSource")
            {
                sourceDBAccess = new DBAccess();
                sourceDBAccess.Server = txtSourceServer.Text;
                sourceDBAccess.Username = txtSourceUsername.Text;
                sourceDBAccess.Password = txtSourcePassword.Text;
            }
            else
            {
                destinationDBAccess = new DBAccess();
                destinationDBAccess.Server = txtDestinationServer.Text;
                destinationDBAccess.Username = txtDestinationUsername.Text;
                destinationDBAccess.Password = txtDestinationPassword.Text;
            }
        }

        private void btnConnectSource_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            LoadDatabaseList(sender as Button);
            Cursor = Cursors.Arrow;
        }

        private void btnConnectDestination_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            LoadDatabaseList(sender as Button);
            Cursor = Cursors.Arrow;
        }

        private void LoadDatabaseList(Button sender)
        {
            InitDBAccess(sender as Button);
            if (sender.Name == "btnConnectSource")
            {
                ArrayList dbList = sourceDBAccess.GetDBList();
                dbList.Insert(0, SelectDatabase);
                cmbSourceDBs.DataSource = dbList;
                cmbSourceDBs.Enabled = true;
            }
            else
            {
                ArrayList dbList = destinationDBAccess.GetDBList();
                dbList.Insert(0, SelectDatabase);
                cmbDestinationDBs.DataSource = dbList;
                cmbDestinationDBs.Enabled = true;
            }
        }

        private void cmbSourceDBs_SelectedIndexChanged(object sender, EventArgs e)
        {
            string value = ((ComboBox)sender).Text;
            if (value != SelectDatabase)
            {
                sourceDBAccess.SqlConnection.ChangeDatabase(value);
                LoadQuestionnaireTypes(cmbSourceQTs);
            }
        }

        private void cmbDestinationDBs_SelectedIndexChanged(object sender, EventArgs e)
        {
            string value = ((ComboBox)sender).Text;
            if (value != SelectDatabase)
            {
                destinationDBAccess.SqlConnection.ChangeDatabase(value);
                LoadQuestionnaireTypes(cmbDestinationQTs);
            }
        }

        private void LoadQuestionnaireTypes(ComboBox combo)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ModuleBit");
            dt.Columns.Add("ModuleName");
            dt.Rows.Add(string.Empty, SelectQuestionnaireType);
            dt.Rows.Add(PHSRAG.Security.Enumerations.ModuleBit.Animals, "Animals");
            dt.Rows.Add(PHSRAG.Security.Enumerations.ModuleBit.COI, "COI");
            dt.Rows.Add(PHSRAG.Security.Enumerations.ModuleBit.Humans, "Humans");

            combo.DataSource = dt;
            combo.ValueMember = "ModuleBit";
            combo.DisplayMember = "ModuleName";
            combo.Enabled = true;
        }

        private void cmbQTs_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cmbSender = (ComboBox)sender;
            if (cmbSender.Enabled && cmbSender.Text != SelectQuestionnaireType)
                LoadQuestionnaires( sender as ComboBox );
        }

        private void LoadQuestionnaires(ComboBox sender)
        {
            IComparer comparer = new QuestionnaireComparer();
            if (sender.Name == "cmbSourceQTs")
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(
                        ConfigurationUserLevel.None);
                config.AppSettings.Settings["Database.Source.UserID"].Value = txtSourceUsername.Text;
                config.AppSettings.Settings["Database.Source.Password"].Value = PHSRAG.Utility.Crypt.EncryptToString( txtSourcePassword.Text );
                config.AppSettings.Settings["Database.Source.Server"].Value = txtSourceServer.Text;
                config.AppSettings.Settings["Database.Source.Catalog"].Value = cmbSourceDBs.Text;
                config.Save();
                ConfigurationManager.RefreshSection("appSettings");

                sourceQuestionnaires = new ArrayList( Questionnaire.GetQuestionnaires((int)Enum.Parse(typeof(PHSRAG.Security.Enumerations.ModuleBit), sender.Text), new NullCachePolicy()).Values );
                sourceQuestionnaires.Sort(comparer);
                dgvSourceQuestionnaires.DataSource = sourceQuestionnaires;
            }
            else
            {
                destinationQuestionnaires = destinationDBAccess.GetQuestionnaires((int)Enum.Parse( typeof(PHSRAG.Security.Enumerations.ModuleBit), sender.Text));
                destinationQuestionnaires.Sort(comparer);
                dgvDestinationQuestionnaires.DataSource = destinationQuestionnaires;
                dgvDestinationQuestionnaires.Refresh();
            }

        }

        private void btnCopySelected_Click(object sender, EventArgs e)
        {
            string message = string.Format( "Are you sure you want to copy the selected Questionnaire(s)?  New Questionnaire(s) / Version(s) will be created{0}.", (chkSetQVActive.Checked) ? ", Version(s) will be set as active." : "" );
            DialogResult oRes = MessageBox.Show(message, "Confirm copy questionnaire(s)", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (oRes == DialogResult.Yes)
            {
                btnCopySelected.Enabled = false;
                Cursor.Current = Cursors.WaitCursor;
                foreach (DataGridViewRow oRow in dgvSourceQuestionnaires.SelectedRows)
                {
                    PHSRAG.Insight21.FormsManagement.Questionnaire sourceQuestionnaire = (PHSRAG.Insight21.FormsManagement.Questionnaire)oRow.DataBoundItem;
                    if (destinationQuestionnaires.Contains(sourceQuestionnaire))
                    {
                        // it's there, so clone the source to destionation
                        Questionnaire destinationQuestionnaire = (Questionnaire)destinationQuestionnaires[destinationQuestionnaires.IndexOf(sourceQuestionnaire)];
                        QuestionnaireVersion sourceQV = null;
                        if (rbActive.Checked)
                            sourceQV = Questionnaire.GetActiveVersion(new NullCachePolicy(), sourceQuestionnaire.Name, sourceQuestionnaire.Type);
                        else if (rbLatest.Checked)
                            sourceQV = (QuestionnaireVersion)sourceQuestionnaire.Versions[sourceQuestionnaire.Versions.Count - 1];
                        destinationQuestionnaire.AddQuestionnaireVersion(sourceQV.Clone(), chkSetQVActive.Checked);
                        destinationQuestionnaire.Save(destinationDBAccess.ConnectionString);
                    }
                    else
                    {
                        // it's not there, so copy the active or latest version
                        PHSRAG.Insight21.FormsManagement.Questionnaire destinationQuestionnaire = sourceQuestionnaire.Clone();
                        QuestionnaireVersion sourceQVClone = null;
                        if (rbActive.Checked)
                            sourceQVClone = Questionnaire.GetActiveVersion(new NullCachePolicy(), sourceQuestionnaire.Name, sourceQuestionnaire.Type).Clone();
                        else if (rbLatest.Checked)
                            sourceQVClone = ((QuestionnaireVersion)sourceQuestionnaire.Versions[sourceQuestionnaire.Versions.Count - 1]).Clone();
                        sourceQVClone.Version = 1;
                        destinationQuestionnaire.Versions.Clear();
                        destinationQuestionnaire.Versions.Add(sourceQVClone);

                        if (cmbDestinationQTs.Text != cmbSourceQTs.Text)
                        {
                            /// We're copying from one moduletype to another, we need to default
                            /// the questionnaire type.
                            switch (cmbDestinationQTs.Text)
                            {
                                case "Animals" :
                                    destinationQuestionnaire.Type = "QUESTTYPE_ANM";
                                    break;
                                case "Humans" :
                                    destinationQuestionnaire.Type = "QUESTTYPE_COI";
                                    break;
                                case "COI" :
                                    destinationQuestionnaire.Type = "QUESTTYPE_CF";
                                    break;
                            }
                            destinationQuestionnaire.ModuleType = (int)Enum.Parse(typeof(PHSRAG.Security.Enumerations.ModuleBit), cmbDestinationQTs.Text);
                        }
                        destinationQuestionnaire.Save(destinationDBAccess.ConnectionString);
                    }
                    LoadQuestionnaires(cmbDestinationQTs);
                }
            }
            Cursor.Current = Cursors.Default;
            btnCopySelected.Enabled = true;
            MessageBox.Show("Copy complete.", "Done");
        }

        private void MigrationMain_Load(object sender, EventArgs e)
        {
            ToolTip toolTip1 = new ToolTip();
            toolTip1.AutoPopDelay = 7000;
            toolTip1.ReshowDelay = 500;
            toolTip1.SetToolTip(chkSetQVActive, "When a Questionnaire exists in the destination, a new QV is created.  Use this option to automatically set the new QV to active and inactivate the currently active QV.");
        }

        private void txtSourcePassword_TextChanged(object sender, EventArgs e)
        {
            if (txtSourcePassword.Text != string.Empty && txtSourceServer.Text != string.Empty && txtSourceUsername.Text != string.Empty)
                btnConnectSource.Enabled = true;
            else
                btnConnectSource.Enabled = false;
        }

        private void txtDestinationPassword_TextChanged(object sender, EventArgs e)
        {
            if (txtDestinationPassword.Text != string.Empty && txtDestinationServer.Text != string.Empty && txtDestinationUsername.Text != string.Empty)
                btnConnectDestination.Enabled = true;
            else
                btnConnectDestination.Enabled = false;
        }

        private void rbActive_CheckedChanged(object sender, EventArgs e)
        {
            rbLatest.Checked = !rbActive.Checked;
        }

        private void rbLatest_CheckedChanged(object sender, EventArgs e)
        {
            rbActive.Checked = !rbLatest.Checked;
        }
    }
}